/**
 * Copyright 2009 - ChunMap
 * 
 * 这个文件是ChunMap项目的一部分。
 * ChunMap是开源软件。
 * 你可以自由复制、传播本项目的下载包文件，但必须保持其完整性。
 * 我们不用对使用中的风险及由此造成的损失承担任何责任。
 * 详细情况请见《ChunMap许可协议》。

 * 想了解更多有关ChunMap的信息，请访问http://code.google.com/p/chunmap/
 */
package chunmap.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author yangjiandong
 * 
 */
public class Reflection {
	public static Object invokeGetter(Object obj, String beanName) {
		try {
			return obj.getClass().getMethod(beanName).invoke(obj);

		} catch (IllegalArgumentException e) {
			throw new ChunDaoException(e);
		} catch (SecurityException e) {
			throw new ChunDaoException(e);
		} catch (IllegalAccessException e) {
			throw new ChunDaoException(e);
		} catch (InvocationTargetException e) {
			throw new ChunDaoException(e);
		} catch (NoSuchMethodException e) {
			throw new ChunDaoException(e);
		}
	}

	public static Method getGetter(Class<?> type, String name) {
		try {
			return type.getMethod(name);
		} catch (SecurityException e) {
			throw new ChunDaoException(e);
		} catch (NoSuchMethodException e) {
			throw new ChunDaoException(e);
		}
	}

	public static Method getSetter(Class<?> type, String name) {
		Method[] ms = type.getMethods();
		for (Method m : ms) {
			if (m.getName().equals(name)) {
				return m;
			}
		}
		return null;
	}

	public static void invokeSetter(Object obj, String beanName, Object value) {
		try {
			if (value == null) {
				return;
			}

			Method[] ms = obj.getClass().getMethods();
			for (Method m : ms) {
				if (m.getName().equals(beanName)) {
					m.invoke(obj, value);
					return;
				}
			}
		} catch (IllegalArgumentException e) {
			throw new ChunDaoException(e);
		} catch (SecurityException e) {
			throw new ChunDaoException(e);
		} catch (IllegalAccessException e) {
			throw new ChunDaoException(e);
		} catch (InvocationTargetException e) {
			throw new ChunDaoException(e);
		}
	}

	public static Object newInstance(Class<?> type) {
		try {
			Object obj = type.newInstance();
			return obj;
		} catch (InstantiationException e) {
			throw new ChunDaoException(e);
		} catch (IllegalAccessException e) {
			throw new ChunDaoException(e);
		}
	}

	public static void setField(Object obj, String fieldName, Object value) {
		try {
			Field field = obj.getClass().getDeclaredField(fieldName);
			field.setAccessible(true);
			field.set(obj, value);

		} catch (IllegalArgumentException e) {
			throw new ChunDaoException(e);
		} catch (SecurityException e) {
			throw new ChunDaoException(e);
		} catch (IllegalAccessException e) {
			throw new ChunDaoException(e);
		} catch (NoSuchFieldException e) {
			throw new ChunDaoException(e);
		}
	}
}
